www.gusucode.com > 基于马尔科夫随机场的图像分割matlab源码。包括ICM迭代条件模式求解最大后验概率算法 > code23/matlab MRF toy examples/testMRF.m

    % testMRF.m
% test the MRF functions.

%%% initPaths;
N=7; M=7;  K_states = 2; prop_mat_beta = 0.2; pFlip = 0.2;

[nodes] = initMRF(N, M, K_states, prop_mat_beta);

image = ones(N,M); image(:,1:round(M/2)) = zeros(N,round(M/2));
noisyImage = addNoise(image, pFlip); 
figure;showIm(image); title('original image');
figure;showIm(noisyImage); title('noisy image');
figure; showIm(nodes{1}.links{1}.propMat, [0, 1]); 
title(['MRF compatibility matrix: ' num2str(1-prop_mat_beta) '   ' num2str(prop_mat_beta) ]);


% initialize local evidence: 
[nodes] = initLocalEvidence(nodes, noisyImage, pFlip);
[nodes] = initBPMessages(nodes, K_states);
figure;
nIter = 40;  maxProductFlag = 0;
for i = 1:nIter
    nodes = oneIterBP(nodes, maxProductFlag);
    nodes = computeBeliefs(nodes);
    im = marginals2image(nodes, 1, N, M);
    showIm(im); title(['after BP MMSE iteration ' num2str(i)]);
end
figure;showIm(im>0.5); title('BP max of the marginals');
%% bpmmLogProb = getLogProb(nodes,N,M,round(real(im>0.5)));

% now do the same thing, but with max product
maxProductFlag = 1;
% re-initialize
[nodes] = initBPMessages(nodes, K_states);
figure;
for i = 1:nIter
    nodes = oneIterBP(nodes, maxProductFlag);
    nodes = computeBeliefs(nodes);
    im = marginals2image(nodes, 1, N, M);
    showIm(im); title(['after BP MAP iteration ' num2str(i)]);
end
figure;showIm(im>0.5); title('BP max product');
%% bpmpLogProb = getLogProb(nodes,N,M,round(real(im>0.5)));

%% % run gbp
%% [gbp] = runGBP(nodes, N, M, K_states, prop_mat_beta, noisyImage);

%% figure;showIm(gbp{1}>0.5); title('gbp max of marginals solution');
%% gbpLogProb = getLogProb(nodes,N,M,round(real(gbp{1}>0.5)));

%% ------------------------------------------------------
%% ICM
nodes = initICM(nodes); figure;
for i = 1:nIter
    nodes = ICM(nodes);
    im = states2image(nodes, 1, N, M);
    showIm(im); title(['after ICM iteration ' num2str(i)]);
end
%% icmLogProb = getLogProb(nodes,N,M,im);
%% ------------------------------------------------------
%% % compare log likelihoods
%% fprintf(1,'BP max marginal: %g  BP MAP: %g  GBP max marginal: %g  ICM: %g\n', ...
%%     bpmmLogProb, bpmpLogProb, gbpLogProb, icmLogProb);